package cn.yhp.mybatis.binding;

import cn.yhp.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author yhp
 * @description Mapper映射器代理类
 * @date 2023/11/8
 */
public class MapperProxy<T> implements InvocationHandler {

    private SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethod> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Object的方法不代理
        if (Object.class.equals(method.getDeclaringClass())){
            return method.invoke(this,args);
        }else {
            final MapperMethod mapperMethod=cacheMapperMethod(method);
            return mapperMethod.execute(sqlSession,args);
        }
    }

    /**
     * 将method方法和对应的MapperMethod对象存入缓存
     * @param method
     * @return
     */
    private MapperMethod cacheMapperMethod(Method method){
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null){
            mapperMethod=new MapperMethod(mapperInterface,method,sqlSession.getConfiguration());
            methodCache.put(method,mapperMethod);
        }
        return mapperMethod;
    }
}
